<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>census</title>
<script src="js/d3.v3.min.js"></script>
<script src="js/d3-queue.v3.min.js"></script>
<script src="js/jquery-3.3.1.min.js"></script>
<link href="css/common.css" rel="stylesheet">
<link href="css/bootstrap.css" rel="stylesheet">
<!--
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://d3js.org/d3-queue.v3.min.js"></script>
-->
</head>
<style>
/*
.show{
    position:absolute;
    z-index: 10;
    color:#7E31A0;
    visibility: :hidden;
    font-size: 12px;
    font-weight: bold;
}
*/
.show {
  position: absolute;
  text-align: center;
  width: 90px;
  height: 28px;
  padding: 2px;
  font: 12px sans-serif;
  background: lightsteelblue;
  border: 0px;
  border-radius: 8px;
}
.but{
  width:600px;
  height:60px;

}
.but button{
  width:100px;
  height:100px;
}
  svg{
    margin-left:180px;
  }
</style>

<body>
<div class=".but">
<select id="day" onchange="gradeDay()">
  <option value="1">day1</option>
  <option value="2">day2</option>
  <option value="3">day3</option>
</select>
<select id="floor" onchange="gradeFloor()">
  <option value="1">floor1</option>
  <option value="2">floor2</option>
</select>
<input id="input1"/>
</div>
	<div style="display: block; margin: 10px auto; width: 924px;">
		<input type="range" id="slider" name="slider" class="ne-range"/>
	</div>
  
<svg id="one" width="1000" height="600">
<!--
<image width="1000" height="600" 
        href="img/first.jpg">
</image>
-->
<!--<image  xlink:href="img/first.jpg" width="1000" height="600"/>-->
</svg>
<svg id="chart"></svg>
<!--
<table class="table">
  <thead>
    <tr>
      <th>区域</th>
      <th>人数</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>room1</td>
      <td>room2</td>
    </tr>
    <tr>
      <td>4</td>
      <td>4</td>
    </tr>
  </tbody>
</table>
-->
<script type="text/javascript">

$("#one").css({"background-image":"url(img/first.jpg)","background-size":"1000px 600px"});
var days=[];
var now=0;
var tp=[];
var tpbefore=[];
var p=[];
var tday=1,tfloor=1;//初始天数和初始楼层
var locations = [];//用以储存感应器数据
//var day = [];//原始的当前选中天数数据
var people;
var person = [];//经处理后的当前天数当前楼层人员数组
for(let i=0;i<10000;i++){
   person[i]=new Array();
}
  
  
  var w = 1000, h = 600;
  var svg=d3.select("#one");
  var g = svg.append("g");

  //var padding = {left: 80, right: 90, top: 62, bottom: 105};//调参调参！！！！！！！！
  var padding = {left: 32, right: 40, top: 62, bottom: 105};//调参调参！！！！！！！！一楼
  //var padding = {left: 32, right: 40, top: 30, bottom: 100};//调参调参！！！！！！！！二楼
  var xScale = d3.scale.linear()
                 .domain([0, 30])
                 .range([padding.left, w - padding.right]);			
  var yScale = d3.scale.linear()
                 .domain([0, 16])
                 .range([padding.top, h - padding.bottom]);
var tooltip = d3.select('body')
              .append('div')
              .attr("class","show")
              .text('');//鼠标悬停在点上显示对应的信息



var q = d3.queue();//用于同时读取多个csv文件
q.defer(d3.csv, "location.csv")
.defer(d3.csv, 'log/day1.csv')
.defer(d3.csv, 'log/day2.csv')
.defer(d3.csv, 'log/day3.csv')
.await(processData);

  

var selectp=[];
var selectps=-1;
var colors=[];
for(let i=0;i<10000;i++){
  colors[i]=0;
}
var precols=["green","#A0522D","#B452CD","#CD3700","#00BFFF","#FF8C00"]
  
function contain(id,selectp){
  for(let i=0;i<selectp.length;i++){
    //console.log("id",id);
    //console.log("selectp[i]",selectp[i]);
    if(id==selectp[i])
      return i;
  }
  return -1;
}
function gradeDay(){
  var objS = document.getElementById("day");
  var day = objS.options[objS.selectedIndex].value;
  tday=parseInt(day);
  //console.log("tday",tday);
  init();
  gothrough();
  draw(now);
}
  
function gradeFloor(){
  var objS = document.getElementById("floor");
  var floor = objS.options[objS.selectedIndex].value;
  tfloor=parseInt(floor);
  //console.log("tfloor",tfloor);
  
  if(tfloor==1){
    $("svg").css({"background-image":"url(img/first.jpg)","background-size":"1000px 600px"});
    padding = {left: 32, right: 40, top: 62, bottom: 105};
  }
  else{
    $("svg").css({"background-image":"url(img/second.jpg)","background-size":"1000px 600px"});
    padding = {left: 32, right: 40, top: 30, bottom: 100};

  }
    xScale = d3.scale.linear()
                 .domain([0, 30])
                 .range([padding.left, w - padding.right]);			
    yScale = d3.scale.linear()
                 .domain([0, 16])
                 .range([padding.top, h - padding.bottom]);

  draw(now);
}

//分钟数转时分
function formatMinutes(strs) {
  let str=parseInt(strs);
  return ((Math.floor(str / 60)).toString().length < 2 ? "0" + (Math.floor(str / 60)).toString() : 
  (Math.floor(str / 60)).toString()) + ":" + ((str % 60).toString().length < 2 ? "0" + (str % 60).toString() : (str % 60).toString());

}    
//秒数转时分秒
function formatSeconds(strs) {
  let str=parseInt(strs);
  let h = Math.floor(str / 3600) < 10 ? '0'+Math.floor(str / 3600) : Math.floor(str / 3600);
  let m = Math.floor((str / 60 % 60)) < 10 ? '0' + Math.floor((str / 60 % 60)) : Math.floor((str / 60 % 60));
  let s = Math.floor((str % 60)) < 10 ? '0' + Math.floor((str % 60)) : Math.floor((str % 60));
  return h + ":" + m + ":" + s;
}     
//通过sid返回楼层及坐标
function coordinate(sid){
  sid=parseInt(sid);
  let floor=parseInt(sid/10000);
  let x=parseInt((sid-floor*10000)/100);
  let y=parseInt((sid-floor*10000-x*100));
  let temp={floor:floor,x:x,y:y};
  return temp;
}   
function gothrough(){
  gothroughRoom();
}
function isIn(sid,fs,xi,xj,yi,yj){
  let tmp=coordinate(sid);
  if(tmp.floor==fs){
    if(tmp.x>=xi&&tmp.x<=xj){
      if(tmp.y>=yi&&tmp.y<=yj){
        return true;
      }
    }
  }
  return false;
}
function isInRoom6(sid){
  return isIn(sid,2,6,7,10,11);
//  let tmp=coordinate(sid);
//  if(tmp.floor==2){
//    if(tmp.x>=6&&tmp.x<=7){
//      if(tmp.y>=10&&tmp.y<=11){
//        return true;
//      }
//    }
//  }
//  return false;
}
function isInRoom4(sid){
  return isIn(sid,1,14,15,25,26);
//  let tmp=coordinate(sid);
//  if(tmp.floor==1){
//    if(tmp.x>=14&&tmp.x<=15){
//      if(tmp.y>=25&&tmp.y<=26){
//        return true;
//      }
//    }
//  }
//  return false;
}
function isInRoom1(sid){
  return isIn(sid,1,6,9,10,11);
//  let tmp=coordinate(sid);
//  if(tmp.floor==1){
//    if(tmp.x>=6&&tmp.x<=9){
//      if(tmp.y>=10&&tmp.y<=11){
//        console.log(sid)
//        return true;
//      }
//    }
//  }
//  return false;
}
function isInRoom2(sid){
  return isIn(sid,1,10,11,10,11);
//  let tmp=coordinate(sid);
//  if(tmp.floor==1){
//    if(tmp.x>=10&&tmp.x<=11){
//      if(tmp.y>=10&&tmp.y<=11){
//        return true;
//      }
//    }
//  }
//  return false;
}
function isInRoom5(sid){
  return isIn(sid,2,10,11,1,5);
}
function isInRoom3(sid){
  return isIn(sid,1,14,15,21,24);
}
function isInRegister(sid){
  return isIn(sid,1,12,13,2,5);
}
function isInMain(sid){
  return isIn(sid,1,2,11,19,28);
}
function isInExi(sid){
  return isIn(sid,1,2,11,15,18);
}
function isInPlay(sid){
  return isIn(sid,2,13,15,0,5);
}
function isInCafeteria(sid){
  return isIn(sid,2,2,9,1,5);
}
function gothroughRoom(){
  let ii=0;
  for(let i=0;i<person.length;i++){
    let len=person[i].length;
    if(len==0)//此位置未使用
      continue;
    let flag6=true,flag2=true,flag5=true,flag4=true;
    let flag=0;
    for(let j=0;j<len;j++){
        

        if(flag6&&isInRoom6(person[i][j].sid)){
          flag6=false;
          
          //ii++;
//          if(colors[person[i][j].id-10000]==0)
//            colors[person[i][j].id-10000]=1;
//          break;
        }
//        if(isIn(person[i][j].sid,1,15,15,7,7)){
//          ii++;
//          //console.log(person[i][j]);
//          colors[person[i][j].id-10000]=2;
//          break;
//        }
        if(flag2&&isInRoom2(person[i][j].sid)){
          flag2=false;
          
          //ii++;
//          if(colors[person[i][j].id-10000]==0)
//            colors[person[i][j].id-10000]=2;
//          break;
        }
        if(flag5&&isInRoom5(person[i][j].sid)){
          flag5=false;
          
//          if(colors[person[i][j].id-10000]==0)
//            colors[person[i][j].id-10000]=3;
//          break;
        }
        if(flag4&&isInRoom4(person[i][j].sid)){
          flag4=false;
          
          //ii++;
//          if(colors[person[i][j].id-10000]==0)
//            colors[person[i][j].id-10000]=4;
//          break;
        }

    }
    if(colors[person[i][0].id-10000]==0){
        if(!flag2)
          colors[person[i][0].id-10000]=2;
        if(!flag5) 
          colors[person[i][0].id-10000]=3;
        if(!flag4)
          colors[person[i][0].id-10000]=4;
        if(!flag6)
          colors[person[i][0].id-10000]=1;   
    }





  }
  //alert(ii)
  
}

//通过person人员数组计算在t时刻floor楼层的人并返回
function numwhent(t,floor){
  let ir=0;
  let irp=[];
  let im=0;
  let imp=[];
  let p=[];
  for(let i=0;i<person.length;i++){
    let len=person[i].length;
    if(len==0)//此位置未使用
      continue;
    if(person[i][0].time>t||person[i][len-1].time+10<t)//对应id的人当前时刻未入场或已经离场
      continue;
    
    
    for(let j=0;j<len;j++){
      //console.log(t+"  "+person[i][j].time);
      if(t>=person[i][j].time&&t<=person[i][j].endtime){

        if(coordinate(person[i][j].sid).floor==floor){
          let tperson={};
          tperson.id=person[i][j].id;
          tperson.sid=person[i][j].sid;
          tperson.time=person[i][j].time;
          tperson.endtime=person[i][j].endtime;
          tperson.admissiontime=person[i][0].time;
          tperson.color=colors[tperson.id-10000];
          
          let flag=true;
          for(let m=j;m>=0;m--){
            if(coordinate(person[i][m].sid).floor!=floor){
              tperson.admissiontime=person[i][m].endtime;
              flag=false;
              break;
            }
          }
          if(flag){
            tperson.admissiontime=person[i][0].time;
          }
          flag=true;
          for(let m=j;m<len;m++){
            if(coordinate(person[i][m].sid).floor!=floor){
              tperson.departuretime=person[i][m].time;
              flag=false;
              break;
            }
          }
          if(flag){
            tperson.departuretime=person[i][len-1].time+10;
          }
          
          p.push(tperson);
          if(isInRegister(tperson.sid)&&colors[tperson.id-10000]==1){
            ir++;
            irp.push(tperson);
          }
          if(isInMain(tperson.sid)&&colors[tperson.id-10000]==1){
            im++;
            imp.push(tperson);
          }    
          
//////////////////////////
          
          
        }
          
        break;
      }
    }
  }
  //p.sort((a, b) => a.admissiontime - b.admissiontime); 
  $("#input1").val(ir);
  return p;
}

function init(){    
    day=days[tday-1];
    console.log("tday",tday);
    console.log("day",day);
  
    for(let i=0;i<10000;i++){
       person[i]=new Array();
    }
  
    //将读到的人员信息添加到全局变量数组person中
    for(let i=0;i<day.length;i++){
        let temp={};
        temp.id=parseInt(day[i].id);
        temp.sid=parseInt(day[i].sid);
        temp.time=parseInt(day[i].time);
        person[temp.id-10000].push(temp);
        
    }
    
    //上一步对于每一个人只添加了开始时间，不方便找结束时间，下面对每一个人每一个时间段进行结束时间的添加
    
    for(let i=0;i<person.length;i++){
        let temp={};
        
        let len=person[i].length;
        if(len==0)//此位置未使用
            continue;
        
        //对id=i+10000的人的所有时间段进行扫描，将后一个时间段的起始时间作为前一个时间段的结束时间并更新至person数组中
        for(let j=1;j<len;j++){
            person[i][j-1].endtime=person[i][j].time-1;
        }
        person[i][len-1].endtime=person[i][len-1].time+10;
        
    }
    console.log("person in ini",person);
}









    


//绘制函数
function draw(tnow){
  svg.selectAll("text").remove();
  svg.selectAll("g").remove();

  p=numwhent(tnow,tfloor);//t时刻第一层楼的人员数组
  
  //console.log(p);
  
  g = svg.append("g");

  g.selectAll("circle")
      .data(p)
      .enter()
      .append("circle")			
      .attr("cx", function(d) {

          return xScale(coordinate(d.sid).y+Math.random()*0.9);
      })
      .attr("cy", function(d) {
          return yScale(coordinate(d.sid).x+Math.random()*0.9);
      })
      //.attr("r", 3)
      .attr("r",function(d,i){
        if(d.color!=0)
          return 5
        else{
          return 3
        }
          
      })
      //.attr("fill","green")
      .attr("fill",function(d){


          return precols[d.color]
    
    
      })
      .on("mouseover",function(d,i){
          d3.select(this)
              .attr("fill","yellow");

          tooltip.style('visibility', 'visible').text("id:"+d.id+"   coordinate("+coordinate(d.sid).x+","+coordinate(d.sid).y+")");
      })
      .on("mousemove",function(d,i){
          tooltip.style('top', (event.pageY-15)+'px').style('left',(event.pageX+7)+'px');
      })
      .on("mouseout",function(d,i){
          d3.select(this)
              .attr("fill",function(d){
                  
                  return precols[d.color];
                });
          d3.select(this)
              .attr("r",function(d){
                if(d.color!=0)
                  return 5
                else
                  return 3
              });
          tooltip.style('visibility', 'hidden');
      })
      .on("click",function(d,i){
          colors[d.id-10000]++;
          colors[d.id-10000]=colors[d.id-10000]%6;
          d.color=colors[d.id-10000];
      });

  
  

  svg.append("text")
    .text(now)
    .attr("x",100)
    .attr("y",125)
    .attr("fill","red")
    .attr("font-size",30);
  svg.append("text")
    .text(formatSeconds(now))
    .attr("x",100)
    .attr("y",100)
    .attr("fill","red")
    .attr("font-size",30);
		


    
    
}
//主处理函数，目前只处理了第一天   	   
function processData(error, data0, data1, data2, data3) {

    locations=data0;
    days=[data1,data2,data3];
    //console.log("days",days);
    
    init();
    gothroughRoom();
    draw(0); 
  

    
    
  

    

  

  
  
  
  
//添加拖动条事件
					$.fn.RangeSlider = function (cfg) {
						this.sliderCfg = {
							min: cfg && !isNaN(parseFloat(cfg.min)) ? Number(cfg.min) : null,
							max: cfg && !isNaN(parseFloat(cfg.max)) ? Number(cfg.max) : null,
							step: cfg && Number(cfg.step) ? cfg.step : 1,
							callback: cfg && cfg.callback ? cfg.callback : null
						};

						var $input = $(this);
						var min = this.sliderCfg.min;
						var max = this.sliderCfg.max;
						var step = this.sliderCfg.step;
						var callback = this.sliderCfg.callback;

						$input.attr('min', min)
							.attr('max', max)
							.attr('step', step)
							.attr('value', 0);

						$input.bind("input", function (e) {
							$input.attr('value', this.value);
							$input.css('background-size', this.value * 100.0 / max + '% 100%');

							if ($.isFunction(callback)) {
								callback(this);
							}
						});
					};


					var change = function ($input) {
						/*拖动滑块的事件，内容可自行定义*/
            now = $("#slider").val();
            

          
            draw(now);
            

            
            
            
            
  
            
            
					};
					$('#slider').RangeSlider({ min: 0, max: 86399, step: 10, callback: change });
}


   </script>
  </body>
</html>






















